package com.da.javatest.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;

public class HolidayUtils {

    public static List<String> getHoliday(int year, int month) {
        Set<String> jjr = JJR(year, month);
        return jjr.stream().sorted().collect(Collectors.toList());
    }

    /**
     * java获取国家法定节假日和周末
     *
     * @param year  /
     * @param month /
     * @return /
     */
    public static Set<String> JJR(int year, int month) {
        //获取所有的周末
        Set<String> monthWekDay = getMonthWekDay(year, month);
        //http://timor.tech/api/holiday api文档地址
        JSONObject jjr = getJjr(year, month);
        Integer code = jjr.getInteger("code");
        if (code != 0) {
            return monthWekDay;
        }
        Map<String, Map<String, Object>> holiday = (Map<String, Map<String, Object>>)jjr.get("holiday");
        Set<String> strings = holiday.keySet();
        for (String str : strings) {
            Map<String, Object> stringObjectMap = holiday.get(str);
            Integer wage = (Integer)stringObjectMap.get("wage");
            String date = (String)stringObjectMap.get("date");
            //筛选掉补班
            if (wage.equals(1)) {
                monthWekDay.remove(date);
            } else {
                monthWekDay.add(date);
            }
        }
        return monthWekDay;
    }

    /**
     * 获取节假日不含周末
     *
     * @param year  /
     * @param month /
     * @return /
     */
    private static JSONObject getJjr(int year, int month) {
        String url = "http://timor.tech/api/holiday/year/" + year + "-" + month;

        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;

    }

    /**
     * 获取周末  月从0开始
     *
     * @param year  /
     * @param month /
     * @return /
     */
    public static Set<String> getMonthWekDay(int year, int month) {
        month = month - 1;
        Set<String> dateList = new HashSet<>();
        SimpleDateFormat simdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar(year, month, 1);
        Calendar endCalendar = new GregorianCalendar(year, month, 1);
        endCalendar.add(Calendar.MONTH, 1);
        while (true) {
            int weekday = calendar.get(Calendar.DAY_OF_WEEK);
            if (weekday == 1 || weekday == 7) {
                dateList.add(simdf.format(calendar.getTime()));
            }
            calendar.add(Calendar.DATE, 1);
            if (calendar.getTimeInMillis() >= endCalendar.getTimeInMillis()) {
                break;
            }
        }
        return dateList;
    }

}

